package com.smartian.scan.filesearch.task.runnable;

import com.smartian.scan.filesearch.bean.SearchResult;
import com.smartian.scan.filesearch.bean.StringPath;
import com.smartian.scan.filesearch.interfaces.ISearchTaskEngine;
import com.smartian.scan.filesearch.interfaces.ITaskCallback;

public class TaskRunnable implements Runnable {

    private ISearchTaskEngine searchTask = null;
    private StringPath path = null;
    private ITaskCallback searchCallback;

    public TaskRunnable(ISearchTaskEngine iSearchTask, String path, ITaskCallback searchCallback) {
        this.searchTask = iSearchTask;
        this.path = new StringPath(path);
        this.searchCallback = searchCallback;
    }

    @Override
    public void run() {
        SearchResult result = null;
        String rootPath  = this.path.getRootPath();
        try {
            if(searchCallback!=null){
                searchCallback.onTaskStart(rootPath);
            }
            SearchResult scanResult = searchTask.doInBackground(rootPath);
            if(scanResult!=null){
                result = StringPath.transform(scanResult,this.path);
            }
        }catch (Exception e){
            e.printStackTrace();
            if(searchCallback!=null){
                searchCallback.onTaskError(rootPath,e);
            }
        }finally {
            if(searchCallback!=null){
                searchCallback.onTaskFiles(rootPath,result);
                searchCallback.onTaskFinish(rootPath);
            }
        }
    }



}
